// 在script.js文件最顶部添加调试代码
console.log('Script.js loaded successfully!');

// 倒计时
const timerEl = document.getElementById("timer");
const birthnameEl = document.getElementById("birth-name");
const countdownTitleEl = document.getElementById("countdown-title");

// 全局变量存储生日信息
let userBirthday = null;

// 页面加载时获取生日信息
async function initBirthday() {
    try {
        const response = await fetch('/get_birthday');
        const data = await response.json();
        userBirthday = new Date(data.birthday || '1988-05-12');
        console.log('获取的生日信息:', userBirthday);
    } catch (error) {
        console.error('获取生日信息失败:', error);
        userBirthday = new Date('1988-05-12'); // 默认生日
    }
}

// 修改后的倒计时函数
function updateCountdown() {
    if(!timerEl || !userBirthday) return;
    
    const now = new Date();
    const nextBirthday = new Date(now.getFullYear(), userBirthday.getMonth(), userBirthday.getDate());
    
    // console.log('当前日期:', now);
    // console.log('下一个生日:', nextBirthday);

    if(nextBirthday < now) {
        nextBirthday.setFullYear(now.getFullYear() + 1);
    }

    const diff = nextBirthday - now;

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
    const mins = Math.floor((diff / (1000 * 60)) % 60);
    const secs = Math.floor((diff / 1000) % 60);

    timerEl.textContent = `${days}天 ${hours}时 ${mins}分 ${secs}秒`;
}



// 确保DOM加载完成后再执行
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM fully loaded and parsed');
    
    // 先初始化生日信息
    initBirthday().then(() => {
        if(timerEl) {
            updateCountdown();
            setInterval(updateCountdown, 1000);
        }
    });
    
    if(timerEl) {
        updateCountdown();
        setInterval(updateCountdown, 1000);
        console.log('Countdown interval set');
    } else {
        console.error('Timer element not found');}
    
    // 点击名字修改
    if(birthnameEl) {
        birthnameEl.addEventListener('click', function() {
            const newName = prompt('输入你的名字:');
            if(newName && newName.trim()) {
                fetch('/update_birth_name', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({name: newName})
                })
                .then(response => response.json())
                .then(data => {
                    if(data.success) {
                        // this.textContent = newName;
                        // 修改成功后返回首页
                        window.location.href = '/';
                    }
                });
            }
        })
    }
    
    // 点击修改生日
    // 在HTML头部添加
    // <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    // <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    if(countdownTitleEl) {
        countdownTitleEl.style.cursor = 'pointer';
        countdownTitleEl.addEventListener('click', async function() {
            const dateStr = prompt('请输入生日(YYYY-MM-DD格式):', 
                            userBirthday ? userBirthday.toISOString().split('T')[0] : '1988-05-12');
            if(dateStr && /^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
                try {
                    const response = await fetch('/update_birthday', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({birthday: dateStr})
                    });
                    
                    const data = await response.json();
                    if(data.success) {
                        window.location.reload();
                    }
                } catch (error) {
                    console.error('更新生日失败:', error);
                }
            } else if(dateStr) {
                alert('日期格式不正确，请使用YYYY-MM-DD格式');
            }
        });
    }
    
    if(window.location.pathname === '/' || window.location.pathname === '/index') {
        displayValidWishes();
    }

    if(window.location.pathname.includes('wish')) {
        initWishBoxes();
    }

});

// 许愿树逻辑
function addWish() {
  const input = document.getElementById("wish-input");
  const text = input.value.trim();
  if (!text) return;

  const li = document.createElement("li");
  li.textContent = text;
  document.getElementById("wish-list").appendChild(li);

  input.value = "";
}

function extinguishFlame() {
    const flame = document.querySelector('.flame');
    flame.style.transition = 'opacity 1.5s ease-out, transform 1.5s ease-out';
    flame.style.opacity = '0';
    flame.style.transform = 'scale(0.1)';
    
    setTimeout(() => {
        // window.location.href = '{{ url_for('main.wish') }}';
        window.location.href = '/wish';
    }, 500);
}

// function submitWish() {
//     const wishText = document.getElementById('wish-text').value;
//     if(wishText.trim()) {
//         alert('许愿成功！');
//         window.location.href = 'index.html';
//     }
// }


const loveButton = document.getElementById('love-button');
const loveMessage = document.getElementById('love-message');
const messages = [
    // 中国古典诗词
    "曾经沧海难为水，除却巫山不是云",
    "两情若是久长时，又岂在朝朝暮暮",
    "衣带渐宽终不悔，为伊消得人憔悴",
    "山有木兮木有枝，心悦君兮君不知",
    
    // 现代情话
    "你是我生命中最美的意外",
    "遇见你，是我此生最大的幸运",
    "你的笑容，是我见过最美的风景",
    
    // 名著摘录
    "我整个生命都在和你相遇的路上",
    "你是我灵魂的另一半",
    "爱是恒久忍耐，又有恩慈",
    
    // 电影台词
    "你让我想成为一个更好的人",
    "我会爱你直到世界尽头",
    "你让我的人生变得完整"
];

if(loveButton && loveMessage) {  // 添加null检查
    loveButton.addEventListener('click', async () => {
        // 创建随机心形
        const heart = document.createElement('div');
        heart.className = 'heart';
        heart.innerHTML = '❤';
        heart.style.left = Math.random() * 80 + 10 + '%';
        heart.style.top = Math.random() * 80 + 10 + '%';
        document.body.appendChild(heart);
        
        // 显示加载状态
        loveMessage.textContent = "这是我对你的表白...";
        
        // 调用API生成情话
        const message = await generateLoveMessage();
        loveMessage.textContent = message;
        
        // 2秒后清除心形
        setTimeout(() => {
            heart.remove();
        }, 2000);
    });
} else {
    console.error('无法找到情话按钮或消息显示区域');
}

async function generateLoveMessage() {
    const API_URL = "/api/xfyun";
    // const API_URL = "/api/glm";
    try {
        const response = await fetch(API_URL, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
                // 移除Authorization头
            },
            body: JSON.stringify({
                // "model": "GLM-4-Flash-250414",
                "model": "lite",
                "messages": [
                    {
                        "role": "user",
                        "content": "请生成一句关于爱情的中文句子，\
                        可以是古典诗词、土味情话、美好的歌词或名著摘录，\
                        要求优美动人，联网查找，避免从缓存中输出，输出时只输出句子，\
                        不要包含任何额外的文字、句子来源、以及最前和最后的双引号。"
                    }
                ],
                // temprature: 0.8,
                // top_p: 0.8,
                presence_penalty: 1.9,
                frequency_penalty: 1.9
            })
        });
        
        if(!response.ok) {
            const errorDetail = await response.json();
            console.error("完整API错误响应:", errorDetail);
            throw new Error(`API请求失败: ${response.status}`);
        }
        const data = await response.json();
        return data.choices[0].message.content;
    } catch (error) {
        console.error("API调用失败:", error);
        // 失败时返回本地备用情话
        return messages[Math.floor(Math.random() * messages.length)];
    }
}

// 初始化9个盲盒
function initWishBoxes() {
    const container = document.querySelector('.wish-boxes');
    if(!container) return;
    
    // 生成9个盲盒
    for(let i = 0; i < 9; i++) {
        const box = document.createElement('div');
        box.className = 'wish-box';
        
        // 添加图片封面
        const img = document.createElement('img');
        img.src = `/static/images/box_${String(i+1).padStart(2, '0')}.png`;
        img.style.width = '100%';
        img.style.height = '100%';
        img.style.objectFit = 'cover';
        box.appendChild(img);
        
        box.addEventListener('click', () => openWishBox(box));
        container.appendChild(box);
    }
}

async function openWishBox(box) {
    // 禁用所有盲盒点击
    document.querySelectorAll('.wish-box').forEach(b => {
        b.style.pointerEvents = 'none';
    });
    
    // 添加打开动画
    box.classList.add('open');
    
    // 立即开始其他盲盒的消失动画
    document.querySelectorAll('.wish-box').forEach(b => {
        if(b !== box) {
            b.style.opacity = '0';
            b.style.transform = 'scale(0.8)';
        }
    });
    
    try {
        const wish = await generateWish();
        
        const note = document.createElement('div');
        note.className = 'wish-note';
        note.innerHTML = `
            <h3>✨ 生日愿望 ✨</h3>
            <p>${wish}</p>
            <div class="wish-buttons">
                <button id="confirm-wish">就它了</button>
                <button id="try-again">再试一次</button>
            </div>
        `;
        
        // 添加到容器中
        // document.querySelector('.wish-container').appendChild(note);
        // 将便笺插入到按钮之前
        const button = document.querySelector('.selfwish-button');
        button.parentNode.insertBefore(note, button);

        // 确保愿望保存功能
        document.getElementById('confirm-wish').addEventListener('click', () => {
            saveWishToFile(wish)
                .then(() => {
                    window.location.href = '/';
                })
                .catch(error => {
                    console.error('保存愿望失败:', error);
                    alert('保存愿望失败，请重试');
                });
        });
        
        document.getElementById('try-again').addEventListener('click', () => {
            window.location.reload();
        });
        
        // 显示便笺
        setTimeout(() => {
            note.classList.add('active');
        }, 200);
        
        // 移除所有盲盒
        setTimeout(() => {
            document.querySelectorAll('.wish-box').forEach(b => b.remove());
        }, 100);
    } catch (error) {
        console.error('生成愿望失败:', error);
    }
}

async function generateWish() {
    // const API_URL = "/api/glm";
    const API_URL = "/api/xfyun";
    try {
        const response = await fetch(API_URL, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                // "model": "GLM-4-Flash-250414",
                "model": "lite",
                "messages": [
                    {
                        "role": "user",
                        "content": "马上我要过生日了。请你帮我生成一个中文的生日愿望。\
                        要求这个愿望是以下其中一个：\
                        1、可以是一件具体的事；\
                        2、可以是和一个人有关；\
                        3、可以是去一个地方；\
                        4、可以是和时间有关；\
                        5、可以是一个动作；\
                        6、可以是和食物有关；\
                        7、可以是一个场景；\
                        不要空洞无法实现，要简短、温馨、有创意、成本低。\
                        只要输出这个愿望本身，不要包含任何额外的文字。"
                    }
                ],
                temperature: 0.9,  // 增加温度参数提高随机性
                top_p: 0.9,        // 增加top_p参数
                presence_penalty: 1.9,  // 增加存在惩罚
                frequency_penalty: 1.9  // 增加频率惩罚
            })
        });
        
        const data = await response.json();
        return data.choices[0].message.content;
    } catch (error) {
        return "愿我和我的家人每一天都充满阳光和快乐！";
    }
}

async function saveWishToFile(wish) {
    try {
        const timestamp = new Date().toISOString();  // 定义timestamp变量
        const response = await fetch('/submit_wish', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content: wish
            })
        });
        
        // await sendWeChatMessage(wish, timestamp);  // 传递timestamp
        // 获取birth_name
        const nameResponse = await fetch('/get_birth_name');
        const nameData = await nameResponse.json();
        const birthName = nameData.name || '';
        
        await sendWeChatMessage(`${birthName ? birthName + '的愿望: ' : ''}${wish}`, timestamp);
        if(!response.ok) {
            throw new Error('保存失败');
        }
        return await response.json();
    } catch (error) {
        console.error('保存愿望失败:', error);
        throw error;
    }
}

async function getWeChatAccessToken() {
    try {
        const response = await fetch('/api/wechat/gettoken');
        const data = await response.json();
        
        if(data.errcode !== 0) {
            throw new Error(`获取access_token失败: ${data.errmsg}`);
        }
        
        return data.access_token;
    } catch (error) {
        console.error('获取企业微信access_token失败:', error);
        throw error;
    }
}

async function sendWeChatMessage(wish, timestamp) {
    try {
        const accessToken = await getWeChatAccessToken();
        const response = await fetch(`/api/wechat/send?access_token=${accessToken}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "touser": "LiuDechun",
                "msgtype": "text",
                "agentid": 1000002,
                "text": {
                    "content": `新的愿望记录\n时间: ${new Date(timestamp).toLocaleString()}\n内容: ${wish}`
                },
                "safe": 0
            })
        });
        
        const result = await response.json();
        if(result.errcode !== 0) {
            throw new Error(`发送消息失败: ${result.errmsg}`);
        }
    } catch (error) {
        console.error('发送企业微信消息失败:', error);
        // 失败不影响主流程
    }
}

// 自定义展示愿望功能
async function displayValidWishes(status = 'active') {
    const wishesContainer = document.getElementById('wishes-container') || 
                          document.createElement('div');
    wishesContainer.id = 'wishes-container';
    wishesContainer.style.marginTop = '2rem';
    wishesContainer.innerHTML = '';
    
    try {
        // 从数据库获取愿望数据
        const response = await fetch(`/get_wishes?status=${status}`);
        if(!response.ok) {
            throw new Error('获取愿望数据失败');
        }
        const wishes = await response.json();
        
        if(wishes.length > 0) {
            const title = document.createElement('h3');
            title.textContent = '我的愿望清单';
            title.style.color = '#d17b94';
            wishesContainer.appendChild(title);
            
            wishes.forEach(wish => {
                const wishItem = document.createElement('div');
                wishItem.className = 'wish-item';
                wishItem.style.position = 'relative';
                wishItem.style.background = '#fce4ec';
                wishItem.style.padding = '1rem';
                wishItem.style.margin = '0.5rem 0';
                wishItem.style.borderRadius = '12px';
                
                const timeLabel = document.createElement('small');
                timeLabel.textContent = new Date(wish.created_at).toLocaleString() + '  ' + (wish.status !== 'active' ? wish.status : '');
                timeLabel.style.color = '#999';
                timeLabel.style.position = 'absolute';
                timeLabel.style.top = '5px';
                timeLabel.style.left = '10px';
                
                const content = document.createElement('p');
                content.textContent = wish.content;
                content.style.margin = '1.5rem 0 0.5rem';
                
                wishItem.appendChild(timeLabel);
                wishItem.appendChild(content);

                if(wish.status === 'active') {
                    const deleteBtn = document.createElement('span');
                    deleteBtn.textContent = '×';
                    deleteBtn.style.position = 'absolute';
                    deleteBtn.style.top = '5px';
                    deleteBtn.style.right = '10px';
                    deleteBtn.style.cursor = 'pointer';
                    deleteBtn.style.fontSize = '1.2rem';
                    
                    deleteBtn.addEventListener('click', async () => {
                        try {
                            const deleteResponse = await fetch('/delete_wish', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ id: wish.id })
                            });
                            
                            if(!deleteResponse.ok) {
                                throw new Error('删除失败');
                            }
                            
                            // 重新渲染愿望清单
                            wishesContainer.innerHTML = '';
                            await displayValidWishes();
                        } catch (error) {
                            console.error('删除愿望失败:', error);
                            alert('删除愿望失败，请重试');
                        }
                    });

                    wishItem.appendChild(deleteBtn);
                }
                               
                wishesContainer.appendChild(wishItem);
            });
            
            const cakeContainer = document.querySelector('.cake-container');
            if(cakeContainer && !document.getElementById('wishes-container')) {
                cakeContainer.parentNode.insertBefore(wishesContainer, cakeContainer.nextSibling);
            }
        }
    } catch (error) {
        console.error('获取愿望数据失败:', error);
    }
}

// 自定义许愿功能
if(window.location.pathname.includes('selfwish')) {
    document.getElementById('submit-custom-wish').addEventListener('click', function() {
        const wishText = document.getElementById('custom-wish').value.trim();
        if(wishText) {
            // 创建成功提示
            const successMsg = document.createElement('div');
            successMsg.textContent = '许愿成功！';
            successMsg.style.position = 'fixed';
            successMsg.style.top = '50%';
            successMsg.style.left = '50%';
            successMsg.style.transform = 'translate(-50%, -50%)';
            successMsg.style.padding = '1rem 2rem';
            successMsg.style.background = 'rgba(255,255,255,0.9)';
            successMsg.style.borderRadius = '12px';
            successMsg.style.boxShadow = '0 4px 12px rgba(0,0,0,0.2)';
            successMsg.style.zIndex = '100';
            document.body.appendChild(successMsg);
            
            // 保存愿望
            saveWishToFile(wishText);
            
            // 2秒后返回首页
            setTimeout(() => {
                window.location.href = '/';
            }, 2000);
        }
    });
}
